<?php

define('APP_ROOT', realpath(__DIR__ . '/../..'));

require_once(APP_ROOT . '/modules/persistance/DBConnector.php');
require_once(APP_ROOT . '/modules/log/log.php');
require_once(APP_ROOT . '/modules/log/logCommon.php');
require_once(APP_ROOT . '/modules/common/Errors.php');
require_once(APP_ROOT . '/modules/common/CommonModule.php');

use persistance\DBConnector;
use log\Log;
use log\LogCommon;
use common\Errors;
use common\CommonModule;

function process($rawIn) {
    Log::LOG_WEBROOTWS_FB();

    if((is_null($rawIn)) ||
       (!is_string($rawIn)) || (empty($rawIn))) {
        Log::LOG_WEBROOTWS(LogCommon::logTypeError, "Invalid parameters.");
        return array('error'=>Errors::INTEGRAL_ERR_INVALID_PARAMETERS);
    }

    $data = json_decode($rawIn, true);
    if((is_null($data)) || (!is_array($data)) ||
        (empty($data))) {
        Log::LOG_WEBROOTWS(LogCommon::logTypeError, "Invalid input json.");
        return array('error'=>Errors::INTEGRAL_ERR_INVALID_JSON);
    }

    $remoteAddress = $_SERVER['REMOTE_ADDR'];
    if(!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $remoteAddress = $remoteAddress . '|' . $_SERVER['HTTP_X_FORWARDED_FOR'];
    }
    if(is_null($remoteAddress) || empty($remoteAddress)) {
        $remoteAddress = 'UNKNOWN';
    }

    $userAgent = $_SERVER['USER_AGENT'];
    if(is_null($userAgent) || empty($userAgent)) {
        $userAgent = 'UNKNOWN';
    }

    DBConnector::connect();
    $cmod = new CommonModule();
    $data = $cmod->login($data['username'], $data['password'],
        $remoteAddress, $userAgent);
    DBConnector::disconnect();

    $rawOut = json_encode($data);
    if((is_null($rawOut)) || (!is_string($rawOut)) ||
        (empty($rawOut))) {
        Log::LOG_WEBROOTWS(LogCommon::logTypeError, "Invalid output json.");
        return array('error'=>Errors::INTEGRAL_ERR_INVALID_JSON);
    }

    Log::LOG_WEBROOTWS_FE();

    return array('error'=>Errors::INTEGRAL_ERR_NONE, 'data'=>$rawOut);
}

function main() {
    Log::LOG_WEBROOTWS_FB();

    if($_SERVER['REQUEST_METHOD'] !== 'POST') {
        Log::LOG_WEBROOTWS(LogCommon::logTypeError, "Invalid request method.");
        header('HTTP/1.1 400 Bad Request', true, 400);
        exit;
    }

    $rawIn = file_get_contents("php://input");
    if((is_null($rawIn)) ||
        (!is_string($rawIn)) || (empty($rawIn))) {
        Log::LOG_WEBROOTWS(LogCommon::logTypeError, "Request data is null or empty.");
        header('HTTP/1.1 400 Bad Request', true, 400);
        exit;
    }

    $rs = process($rawIn);
    if((is_null($rs)) ||
       (is_null($rs['data'])) || (empty($rs['data']))) {
        Log::LOG_WEBROOTWS(LogCommon::logTypeError, "Response data is null or empty.");
        header('HTTP/1.1 500 Internal Server Error', true, 500);
        exit;
    }

    print($rs['data']);
    header('HTTP/1.1 200 OK', true, 200);

    Log::LOG_WEBROOTWS_FE();

    exit;
}

main();
